<template>
  <view class="vback">
    <view class="container">
      <!-- 聊天记录 -->
      <view class="chat-history">
        <view
          v-for="(item, index) in chatHistory"
          :key="index"
          :class="{
            'message-left': item.From === 1,
            'message-right': item.From === 0,
          }"
        >
          <view
            class="message"
            :class="{
              'message-left': item.From === 1,
              'message-right': item.From === 0,
            }"
          >
            {{ item.Message }}
          </view>
          <image
            :src="item.avatar"
            class="avatar"
          />
        </view>
      </view>

      <!-- 发送消息 -->
      <view class="chat-input">
        <button @click="close" class="end">结束</button> <!-- 新增的结束对话按钮 -->
        <textarea
          v-model="message"
          placeholder=""
          @keyup.enter="sendMessage"
        />
        <button @click="sendMessage">
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {WebSocketBean} from 'tools-vue3'
import {IWebSocketBeanParam} from 'tools-vue3/src/websocket/websocket'
import {reactive,ref} from 'vue'
import { useRoute } from 'vue-router';
class MyDate extends Date {
  format(fmt: string): string {
    const o: { [key: string]: any } = {
      "M+": this.getMonth() + 1,
      "d+": this.getDate(),
      "h+": this.getHours(),
      "m+": this.getMinutes(),
      "s+": this.getSeconds(),
      "q+": Math.floor((this.getMonth() + 3) / 3),
      "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  }
}
let message = ref('')
const route = useRoute()

enum MessageType {
  /**
   * 收到发来的消息
   */
  Get,
  /**
   * 发送到服务器的消息
   */
  Send,
  /**
   * 通知
   */
  Message
}
const conf = reactive({
  status: '未连接',
  messagetype: {
    [MessageType.Get]: '收到',
    [MessageType.Send]: '发送',
    [MessageType.Message]: '通知'
  } as any,
  message: [] as {
    time: any
    type: MessageType
    data: any
  }[],
  // url: `ws://your-websocket-url?token=${token.value}`,
  url: `ws://127.0.0.1:8001/ws?token=${window.localStorage.userId}`,
  send: {
    Time:'',
    Data: {
      Email: "",
      Username: "",
      UserId: window.localStorage.userId,
      Shopid: route.query.id,
      message: "",
      From: "0",
    }
  }
}
)
const getParam = () => {
  return {
    url: conf.url,
    needReconnect: true,
    reconnectGapTime: 5000,
    heartSend: '~',
    heartGet: '~',
    heartGapTime: 5000,
    onopen: () => {

    },
    onmessage: (data: any) => {
      console.log(data.data)
      let sp = JSON.parse(data.data)
      console.log(sp)
     chatserve.push({Time:new Date().getTime() * 0.001,From:1,userId:sp.data.UserId,Message:sp.data.message,Shopid:sp.data.Shopid})
     console.log(chatserve)
      chatHistory.value.push({
           From: 1,
           avatar: '../../static/logo.png',
           Message: `${sp.data.message}`
         })
    },
    onerror: () => {
    }
  } as IWebSocketBeanParam
}

/**
 * websocket示例，主要维护和使用对象
 */
let chatHistory=ref([])
const ws = new WebSocketBean(getParam())
const start = () => {
  ws.start(getParam())
  ws.status = 1
}
let chatserve=[]
const close = () => {
  console.log(Math.round(new Date().getTime() * 0.001))
  console.log(chatserve)
  http.request({
        url: '/msg/save',
        method: 'POST',
        data:chatserve
      })
  console.log('1')
  ws.dispose()

  alert('关闭连接成功')
}
const gethistory = () => {
  http.request({
    url: '/msg/GetByUserIdAndShopId',
    method: 'POST',
    data: {userId: window.localStorage.userId, Shopid: conf.send.Data.Shopid}
  })
  .then(({ data }) => {
    console.log('2')
    console.log(data)
    // 遍历数据并添加新元素
    let newdata=[]
    data.forEach(item => {
      if (item.From === 0) {
        item.avatar = '../../static/images/icon/head04.png';
      } else if (item.From === 1) {
        item.avatar = '../../static/logo.png';
      }
    });
    console.log(data)
    chatHistory.value = data;
  })
}

const sendMessage = () => {
  conf.send.Data.message = message.value;
  if(message.value===''||message.value==='\n'){
    alert('消息不能为空')
  }
  else if (ws.status === 1) {
    console.log(conf.send)
    const sendStatus = ws.send(conf.send)
    chatserve.push({Time:new Date().getTime() * 0.001,From:0,userId:conf.send.Data.UserId,Message:conf.send.Data.message,Shopid:conf.send.Data.Shopid})
    console.log(chatserve)
    console.log(route)
    if (sendStatus) {
      chatHistory.value.push({
           From: 0,
           avatar: '../../static/images/icon/head04.png',
           Message: `${message.value}`
         })
      message.value = ''
    }
  } else {
    alert('未连接')
  }
}
start();
gethistory();
</script>

<style scoped lang="scss">
@use "./chat.scss";
</style>
